/*
*/

Include("data/scripts/scene_table.nut")

class	ProjectHandler
{
	dispatch				=	0
	scene_table_index		=	0
	scene					=	0
	iteration_count			=	0
	display_timeout			=	0
	frame_buffer			=	0
	
	function	OnUpdate(project)
	{
		dispatch(project)
	}

	function	OnSetup(project)
	{
		print("ProjectHandler::OnSetup()")
		g_scene_table.sort()
		frame_buffer = PictureNew()
		display_timeout = g_clock
	}

	function	LoadNextTest(project)
	{
		print("ProjectHandler::LoadNextTest()")
		if (scene_table_index >= g_scene_table.len())
		{
			ProjectEnd(project)
			return
		}

		if (scene != 0)	
		{
			ProjectUnloadScene(project, scene)
			ResourceFactoryPurge(g_factory)
		}

		local	scene_filename = "data/scenes/" + g_scene_table[scene_table_index] + ".nms"

		if (FileExists(scene_filename))
		{
			print("ProjectHandler::LoadNextTest('" + scene_filename + "')")
			scene = ProjectInstantiateScene(project, scene_filename)
			ProjectAddLayer(project, scene, 0.5)
		}
		else
			error("ProjectHandler::LoadNextTest() Could not find '" + scene_filename + "'.")

		dispatch = FirstSceneUpdate
	}

	function	FirstSceneUpdate(project)
	{
		iteration_count++
		if (iteration_count > 4)
		{
			iteration_count = 0
			dispatch = SnapshotScene
		}
	}

	function	SnapshotScene(project)
	{
		local	snapshot_filename = "snapshots/" + g_scene_table[scene_table_index] + ".tga"
		print("ProjectHandler::SnapshotScene('" + snapshot_filename + "')")
		RendererGrabDisplayToPicture(g_render, frame_buffer)

		try
			PictureSaveTGA(frame_buffer, snapshot_filename)
		catch(e)
			print(e)

		dispatch = IncrementSceneIndex
	}

	function	IncrementSceneIndex(project)
	{
		scene_table_index++
		dispatch = MainUpdate
	}
	
	function	MainUpdate(project)
	{
		if ((scene == 0) || (g_clock - display_timeout > SecToTick(Sec(2.0))))
		{
			display_timeout = g_clock
			dispatch = LoadNextTest
		}
	}
	
	constructor()
	{
		print("ProjectHandler::constructor()")
		dispatch = MainUpdate
	}
}
